/*
 * @Author: CPS
 * @Date: 2020-07-16 12:24:53
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-26 23:33:02
 * @Projectname Electron-fileWatcher
 * @Filename electron.api.js
 * 封装常用的跟主进程通讯的模块
 * 封装常用的全局模块
 */

'use strict'

const worker = require('worker_threads');

const ipcRenderer = require('electron').ipcRenderer;
const remote = require('electron').remote;

const dialog = remote.dialog;
const win = remote.getCurrentWindow();
const app = remote.app;
const screen = remote.screen;
const display = screen.getPrimaryDisplay() //获取主屏幕信息
const width = display.bounds.width
const height = display.bounds.height

const config = require('@app/fielWatcherObject')

/**
 * 系统弹出框，返回一个promiss
 *
 * @param      {<type>}    settings  文件筐的属性，对应electron的api
 * @param      {Function}  callback  回调函数
 */
function showDialog(settings, callback) {
  let data = {
    type: 1, //1 系统原生文件选择框
    title: '测试窗口',
    defaultPath: '',
    properties: ['openFile', 'openDirectory'], //文件夹和文件
    filters: [{
      name: 'all-files',
      extensions: ['*']
    }]
  }

  // 更新自定义的配置到文件夹框
  if (settings) {
    Object.assign(data, settings)

    // 模样目录为软件所在目录
    if (!data['properties']) data['properties'] =
      config['loaclSettings']['appPath']
  }

  // 根据类型生成不同的弹窗
  // 1 - 系统原生文件选择框 - electronAPI
  // 2 - 使用js模块,调用第三方
  switch (data.type) {
    case 1:
      // 调用对话框，并传入回调函数
      dialog.showOpenDialog(data)
        .then(res => {
          if (!res.canceled) {
            callback(res.filePaths)
          }
        })

      break;
    default:
      // statements_def
      break;
  }
}

// 触发渲染进程事件
function send(tar, args) {
  ipcRenderer.sendTo(1, tar, args)
}

// 触发主进程事件
function sendMain(tar, args) {
  ipcRenderer.send(tar, args)
}

//渲染进程间触发事件
function sendChannel(channel, tar, args) {
  ipcRenderer.sendTo(channel, tar, args)
}

// 监听事件
function on(action, callback) {
  ipcRenderer.on(action, callback)
}

// 触发事件
function emit(action, data) {

}


module.exports = (() => {
  log('载入electron.api.js1')
  if (global.YYS) {
    return global.YYS
  }
  global.YYS = {
    win: win,
    id: win.id,
    hwnd: new Int32Array(win.getNativeWindowHandle().buffer).toString(), //主窗口的句柄
    config: config, //默认配置接口
    worker: worker, //工作线程模组
    showDialog: showDialog, //选择文件/文件夹加框
    send: send, //发送事件到渲染进程
    sendMain: sendMain, //发送事件到主进程
    sendChannel: sendChannel, //渲染进程间触发事件
    on: on, //事件监听接口
    width, //输出桌面的长和宽
    height, //输出桌面的长和宽
  }
  return global.YYS
})()